<?php
namespace StarCloud\Services;

use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Di;
use StarCloud\Library\Config;
use Framework\DiServices\HttpClient;
use Framework\DiServices\Queue;
use Phalcon\Logger\Adapter\File;
use StarCloud\Library\SentryException;
use StarCloud\Library\Sms\AbstractSmsClient;
use StarCloud\Models\Base;

abstract class BaseService
{
    public static function getDb($dbName = 'db') : Mysql
    {
        return Di::getDefault()->getShared($dbName);
    }

    public static function getRedis() : \Redis
    {
        return Di::getDefault()->get('redis');
    }

    public static function getSmsClient($name = 'aliyunSms') : AbstractSmsClient
    {
        return Di::getDefault()->get($name);
    }

    public static function getQueue() : Queue
    {
        return Di::getDefault()->get('queue');
    }

    public static function getLogger() : File
    {
        return Di::getDefault()->get('logger');
    }

    public static function getConfig() : Config
    {
        return Di::getDefault()->get('config');
    }

    public static function getHttpClient() : HttpClient
    {
        return Di::getDefault()->get('httpClient');
    }

    public static function simpleTransactionHealthy($function, $dbName = 'healthy')
    {
        try {
            $db = self::getDb($dbName);
            $db->begin();

            call_user_func($function);

            $db->commit();

            return true;
        } catch (\Exception $e) {
            $db->rollback();

            self::getLogger()->error('Transaction error: ' . $e->getFile() . $e->getLine() . $e->getMessage() . $e->getTraceAsString());

            throw new SentryException('10001');
        }
    }

    public static function simpleTransaction($function, $dbName = 'db')
    {
        try {
            $db = self::getDb($dbName);
            $db->begin();

            call_user_func($function);

            $db->commit();

            return true;
        } catch (\Exception $e) {
            $db->rollback();

            self::getLogger()->error('Transaction error: ' . $e->getMessage() . $e->getTraceAsString());

            throw new SentryException('10001');
        }
    }

    public static function softDelete(Base $model)
    {
        return $model->softDelete();
    }

    public static function switchStatus(Base $model)
    {
        return $model->switchStatus();
    }
}
